<?php

namespace Portal\Controller;
use Common\Controller\HomebaseController; 
/**
 * 首页
 */
class IndexController extends HomebaseController {
	
    //系统首页
	public function index() {
		$this->checkuser();
		$user = session('user');
		$data["user"] = $user;
		//总库存
		$kucun_model = M("kucun");
		$data['allkucun'] = $kucun_model->where("statue=1 AND uid ='".$user['id']."'")->sum("booknum");
		
		
		$this->assign('data',$data);
    	$this->display("book:index");
    }
	
	//系统数据首页
	public function home() {
		$this->checkuser();
		$user = session('user');
		
		//昨日入库
		$todayzero = date("Y-m-d");//今天凌晨
		$yesterdayzero = date("Y-m-d",strtotime($todayzero)-3600*24);
		$outlist_model = M("kucun_outlist");
		$kucun_model = M("kucun");
		$where["statue"] = 1;
		$where["uid"] = $user['id'];
		$where['addtime'] = array(array('gt',$yesterdayzero),array('lt',$todayzero), 'and') ;
		$data['yesterdayin'] = $kucun_model->where($where)->count();
		
		//昨日出库
		unset($where);
		$where["statue"] = 2;
		$where["uid"] = $user['id'];
		$where['outtime'] = array(array('gt',$yesterdayzero),array('lt',$todayzero), 'and') ;
		$data['yesterdayout'] = $outlist_model->where($where)->count();
		
		//今日入库
		unset($where);
		$where["statue"] = 1;
		$where["uid"] = $user['id'];
		$where['addtime'] = array("gt",$todayzero);
		$data['todayin'] = $kucun_model->where($where)->count();
		
		//今日出库
		unset($where);
		$where["statue"] = 2;
		$where["uid"] = $user['id'];
		$where['outtime'] = array("gt",$todayzero);
		$data['todayout'] = $outlist_model->where($where)->count();
		
		//最近入库
		unset($where);
		$where["statue"] = 1;
		$where["uid"] = $user['id'];
		$data['inlist'] = $kucun_model->where($where)->order("id desc")->limit(10)->select();
		
		//最近出库
		unset($where);
		$where["statue"] = 2;
		$where["uid"] = $user['id'];
		$data['outlist'] = $outlist_model->where($where)->order("outtime desc")->limit(10)->select();
		
		$this->assign('data',$data);
    	$this->display("book:home");
    }
	
	//清空库存信息
	public function delkucun(){
		$this->checkuser();
		$user = session('user');
		$pwd = I('get.pwd','');
		//核对登录密码
		$pwd = sp_password($pwd);
		if($pwd!=$user['user_pass']){
			$this->error("密码错误！");
			exit();
		}
		$kucun_model = M("kucun");
		$kucun_model->where("1")->delete();
		$this->success("库存清空完成！");
	}
	
	//删除图书库存记录
	public function delbook(){
		$this->checkuser();
		$user = session('user');
		$kucunid = I('get.kucunid','');
		if(empty($kucunid)){
			$this->error("库存ID没有传递，返回请求页面！");
			exit();
		}
		$kucun_model = M("kucun");
		$where["uid"] = $user['id'];
		$where["id"] = $kucunid;
		$check = $kucun_model->where($where)->count();
		if(empty($check)){
			$this->error("库存ID不存在或者该书不属于您！");
			exit();
		}
		$kucun_model->where($where)->delete();
		$this->success("删除成功！");
	}
	
	//生成出库方案
	public function printlist() {
		$this->checkuser();
		$user = session('user');
		
		$starttime = I('get.starttime','');
		$endtime = I('get.endtime','');
		$orderby = I('get.orderby','');
		$orderway = I('get.orderway','');
		$isprint = I('get.isprint','');
		
		$data['orderby'] = $orderby;
		if(empty($orderway)){
			$orderway ="DESC";
			$data['orderway'] = "ASC";
			$data['orderby'] = $orderby;
		}else{
			$data['orderway'] = $orderway=="ASC"?"DESC":"ASC";
			$data['orderby'] = $orderby;
		}
		$orderby = empty($orderby)?" outtime ".$orderway:$orderby." ".$orderway;
		
		
		$outlist_model = M("kucun_outlist");
		if(!empty($starttime)){
			$starttime = $starttime;
		}else{
			$starttime = date('Y-m-d 00:00');
		}
		if(!empty($endtime)){
			$endtime = $endtime;
		}else{
			$endtime = date('Y-m-d 59:59');
		}
		
		$where["uid"] = $user['id'];
		if(!empty( $isprint )){
			if($isprint=="2"){
				$where['isprint'] = array('EXP','IS NULL');
			}else{
				$where['isprint'] = array('EGT',0);
			}
		}
		$data['isprint'] = $isprint;
		$where["outtime"] = array(array('EGT',$starttime),array('ELT',$endtime),'and'); 
		
		$data['starttime'] = $starttime;
		$data['endtime'] = $endtime;
		$data['count'] = $outlist_model->where($where)->sum('booknum');
		$data['list'] = $outlist_model->where($where)->order($orderby)->select();
		//echo $outlist_model->getlastsql();
		$this->assign('data',$data);
		$this->display("book:printlist");
	}
	
	//打印出库方案
	public function printlistsure() {
		$this->checkuser();
		$user = session('user');
		
		$starttime = I('get.starttime','');
		$endtime = I('get.endtime','');
		$orderby = I('get.orderby','');
		$orderway = I('get.orderway','');
		$isprint = I('get.isprint','');
		
		$data['orderby'] = $orderby;
		if(empty($orderway)){
			$orderway ="DESC";
			$data['orderway'] = "ASC";
			$data['orderby'] = $orderby;
		}else{
			$data['orderway'] = $orderway=="ASC"?"DESC":"ASC";
			$data['orderby'] = $orderby;
		}
		$orderby = empty($orderby)?" outtime ".$orderway:$orderby." ".$orderway;
		
		
		if(!empty($starttime)){
			$starttime = $starttime;
		}else{
			$starttime = date('Y-m-d 00:00');
		}
		if(!empty($endtime)){
			$endtime = $endtime;
		}else{
			$endtime = date('Y-m-d 59:59');
		}
		$temp_model = M("kucun_outlist");
		$where["uid"] =  $user['id'];
		if(!empty( $isprint )){
			if($isprint=="2"){
				$where['isprint'] = array('EXP','IS NULL');
			}else{
				$where['isprint'] = array('EGT',0);
			}
		}
		$where["outtime"] = array(array('EGT',$starttime),array('ELT',$endtime),'and'); 
		$data['count'] = $temp_model->where($where)->sum("booknum");
		$data['list'] = $temp_model->where($where)->order($orderby)->select();
		//echo $temp_model->getlastsql();
		$this->assign('data',$data);
		$this->display("book:printlist_sure");
	}
	
	//设置出库单已经打印
	public function printend() {
		$this->checkuser();
		$user = session('user');
		$kucun_model = M("kucun");
		$outlist_model = M("kucun_outlist");
		
		$where["uid"] = $user['id'];
		$data["isprint"] = "1";//设置为已经打印
		$outlist_model->where($where)->save($data);
		$where["uid"] = $user['id'];
		$this->success("打印完成，数据更新完成！",U("index/printlist"));
	}
	
	//批量入库
	public function ruku() {
		$this->checkuser();
		$user = session('user');
		//分页
		$page = I('get.page','');
		$page = empty($page)?1:$page;
		$pagesize = 20;
		$start = ($page-1)*$pagesize;
		$limitstr = $start.",".$pagesize;
		
		$kucun_model = M("kucun");
		$data['list'] = $kucun_model->where("statue=1 AND uid ='".$user['id']."'")->order("id desc ")->limit($limitstr)->select();
		$data['count'] = $kucun_model->where("statue=1 AND uid ='".$user['id']."'")->count();
		$data['total'] = ceil($data['count']/$pagesize);
		$data['page'] = $page;
		$pageurl = U("index/ruku");
		$data['pageurl'] = $pageurl;
		
		$this->assign('data',$data);
    	$this->display("book:ruku");
    }
	
	//图书快速入库
	public function ruku_one(){
		$this->checkuser();
		$user = session('user');
    	$this->display("book:ruku_one");
	}
	
	//图书快速入库逻辑
	public function ruku_one_action(){
		$this->checkuser();
		$user = session('user');
		
		$isbnstr = trim(I('post.isbn',''));
		$data["uid"] = $user['id'];
		$data["statue"] = 1;
		$data["addtime"] = date("Y-m-d H:i:s");
		$data['booknum'] = I('post.booknum','');
		$data['location'] = I('post.location','');
		if(empty($isbnstr)){
			$this->error("ISBN不能为空！");
			exit();
		}
		if(empty($data['booknum'])){
			$this->error("图书数量不能为空！");
			exit();
		}
		if(empty($data['location'])){
			$this->error("请输入图书库位！");
			exit();
		}
		
		$isbnarr = explode(",",$isbnstr);
		foreach( $isbnarr as $key=>$val ){
			if(empty($val)){
				continue;
			}
			if(!is_numeric($val)){
				continue;
			}
			$data['isbn'] = $val;
			$kucun_model = M("kucun");
			$info = $kucun_model->where("isbn=".$val)->find();
			if(!empty($info["bookname"])){
				$data["bookname"] = $info["bookname"];
				$data["image"] = $info["image"];
				$data["bookname"] = $info["bookname"];
				$data["publisher"] = $info["publisher"];
				$data["price"] = $info["price"];
			}
			$kucun_model->where($where)->add($data);
		}
		die("1");
		
	}
	
	/*库存数据上传操作*/
	public function up(){
		$this->checkuser();
		$user = session('user');
		
		if ( !empty($_FILES) ) {
			$upload_setting=sp_get_upload_setting();
			$filetypes=array(
				'image'=>array('title'=>'Image files','extensions'=>$upload_setting['image']['extensions']),
				'video'=>array('title'=>'Video files','extensions'=>$upload_setting['video']['extensions']),
				'audio'=>array('title'=>'Audio files','extensions'=>$upload_setting['audio']['extensions']),
				'file'=>array('title'=>'Custom files','extensions'=>$upload_setting['file']['extensions'])
			);
			$all_allowed_exts=array();
            foreach ($filetypes as $mfiletype){
                array_push($all_allowed_exts, $mfiletype['extensions']);
            }
            $all_allowed_exts=implode(',', $all_allowed_exts);
            $all_allowed_exts=explode(',', $all_allowed_exts);
            $all_allowed_exts=array_unique($all_allowed_exts);
			
			$file_extension = sp_get_file_extension($_FILES['file']['name']);
            $upload_max_filesize=$upload_setting['upload_max_filesize'][$file_extension];
            $upload_max_filesize=empty($upload_max_filesize)?30485760:$upload_max_filesize;//默认10M
			$savepath='/ruku/'.date('Ymd').'/';
            //上传处理类
            $config=array(
            		'rootPath' => './'.C("UPLOADPATH"),
            		'savePath' => $savepath,
            		'maxSize' => $upload_max_filesize,
            		'saveName'   =>    array('uniqid',''),
            		'exts'       =>    $all_allowed_exts,
            		'autoSub'    =>    false,
            );
			$upload = new \Think\Upload($config);// 
			$info=$upload->upload();
            //开始上传
            if ($info) {
                //上传成功
                $oriName = $_FILES['file']['name'];
                //写入附件数据库信息
                $first = array_shift($info);
				$url = C("TMPL_PARSE_STRING.__UPLOAD__").$savepath.$first['savename'];
				$full_path = SITE_PATH.$url;
				$preview_url = $url;
				
				//执行数据导入
				ini_set('memory_limit', '556M');
				ini_set('max_execution_time', '0');
				vendor('PHPExcel.PHPExcel');
				vendor('PHPExcel.PHPExcel.IOFactory');
				$objReader = \PHPExcel_IOFactory::createReader('Excel5');
				$objPHPExcel = $objReader->load($full_path,$encode='utf-8');
				$data = '';
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow(); // 取得总行数
				$highestColumn = $sheet->getHighestColumn(); // 取得总列数
				for($i=2;$i<=$highestRow;$i++)
				{
					$data[$i]["isbn"] = trim($objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue());
					$data[$i]["location"] = strtoupper($objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue());
					$data[$i]["booknum"] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
					$data[$i]["bookname"] = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
					$data[$i]["price"] = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
					
					if(empty($data[$i]["isbn"]))continue;
					$data[$i]["uid"] = $user['id'];
					$data[$i]["statue"] = 1;
					$data[$i]["addtime"] = date("Y-m-d H:i:s");
					$kucun_model = M("kucun");
					$kucun_model->add($data[$i]);
				}
				
				$this->ajaxReturn(array('code'=>'1','msg'=>"导入成功！",'status'=>1));
				
            } else {
                $this->ajaxReturn(array('name'=>'','status'=>0,'message'=>$upload->getError()));
            }
		}else{
			$this->error("文件未上传！");
		}
    }
	
	
	/*库存导入错误后修复处理*/
	public function repairkucun(){
		$this->checkuser();
		$user = session('user');
		die("关闭这个功能！");
		//处理文件
		$full_path = SITE_PATH.C("UPLOADPATH")."repair.xls";
		
		//执行数据导入
		ini_set('memory_limit', '556M');
		ini_set('max_execution_time', '0');
		vendor('PHPExcel.PHPExcel');
		vendor('PHPExcel.PHPExcel.IOFactory');
		$objReader = \PHPExcel_IOFactory::createReader('Excel5');
		$objPHPExcel = $objReader->load($full_path,$encode='utf-8');
		$data = '';
		$sheet = $objPHPExcel->getSheet(0);
		$highestRow = $sheet->getHighestRow(); // 取得总行数
		$highestColumn = $sheet->getHighestColumn(); // 取得总列数
		for($i=2;$i<=$highestRow;$i++)
		{
			$data[$i]["isbn"] = trim($objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue());
			$data[$i]["location"] = strtoupper($objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue());
			$data[$i]["booknum"] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
			if(empty($data[$i]["isbn"]))continue;
			
			$where["isbn"] = $data[$i]["isbn"];
			$where["location"] = $data[$i]["location"];
			$kucun_model = M("kucun");
			$kucun_model->where($where)->setDec('booknum',$data[$i]["booknum"]);
			
		}
		
    }
	
	
	//图书信息自动抓取入库
	public function updateisbninfo(){
		$isbn = I("get.isbn");
		if(empty($isbn)){
			$this->ajaxReturn(array('status'=>0,'message'=>"ISBN编码未传递！"));
			exit();
		}
		if(!is_numeric($isbn)){
			$this->ajaxReturn(array('status'=>0,'message'=>"ISBN编码错误！"));
			exit();
		}
		
		//监测api使用次数
		$api_model = M("kucun_apitimes");
		$apiinfo = $api_model->where(1)->find();
		$nowtime = strtotime("now");
		$allowtime = strtotime($apiinfo['allowtime']);;
		if( $nowtime>$allowtime  ){
			if( $apiinfo['nowtimes']>101 ){
				$nextallowtime = $nowtime+60;
				$data["allowtime"] = date("Y-m-d H:i:s",$nextallowtime);
				$data["nowtimes"] = 1;
				$api_model->where(1)->save($data);
				
				$this->ajaxReturn(array('status'=>3,'message'=>"API使用次数有限，暂被锁定！"));
				exit();
			}
		}else{
			$this->ajaxReturn(array('status'=>3,'message'=>"API使用次数有限，暂被锁定！"));
			exit();
		}
		
		//更新前先查询下isbn信息是否在数据库中存在
		$kucun_model = M("kucun");
		$info = $kucun_model->where("isbn=".$isbn)->find();
		if(!empty($info["bookname"])){
			//该书信息已经入库，直接取数据库中的值
			$data["image"] = $info["image"];
			$data["bookname"] = $info["bookname"];
			$data["publisher"] = $info["publisher"];
			$data["price"] = $info["price"];
			$kucun_model->where("isbn=".$isbn)->save($data);
			die($info);
		}
		
		$url = "https://api.douban.com/v2/book/isbn/".$isbn;
		$info = $this->GetDouBanAPI($url);
		$bookinfo = json_decode($info,1);
		if(!is_array($bookinfo)){
			$this->ajaxReturn(array('status'=>0,'message'=>"图书信息获取异常！"));
			exit();
		}
		$data["bookname"] = $bookinfo['title'];
		if($bookinfo['msg'] =="book_not_found"){
			$data['bookname'] = "";
		}
		
		$data["price"] = $bookinfo['price'];
		$data["publisher"] = $bookinfo['publisher'];
		$data["image"] = $bookinfo['image'];
		
		if(empty($data["bookname"])){
			$this->ajaxReturn(array('status'=>0,'message'=>"图书信息获取异常！"));
			exit();
		}
		$kucun_model->where("isbn=".$isbn)->save($data);
		$outlist_model = M("kucun_outlist");
		$outlist_model->where("isbn=".$isbn)->save($data);
		$api_model->where(1)->setInc("nowtimes",1);
		die($info);
	}
	
	/*ISBN数据上传操作*/
	public function upisbn(){
		$this->checkuser();
		$user = session('user');
		
		if ( !empty($_FILES) ) {
			$upload_setting=sp_get_upload_setting();
			$filetypes=array(
				'image'=>array('title'=>'Image files','extensions'=>$upload_setting['image']['extensions']),
				'video'=>array('title'=>'Video files','extensions'=>$upload_setting['video']['extensions']),
				'audio'=>array('title'=>'Audio files','extensions'=>$upload_setting['audio']['extensions']),
				'file'=>array('title'=>'Custom files','extensions'=>$upload_setting['file']['extensions'])
			);
			$all_allowed_exts=array();
            foreach ($filetypes as $mfiletype){
                array_push($all_allowed_exts, $mfiletype['extensions']);
            }
            $all_allowed_exts=implode(',', $all_allowed_exts);
            $all_allowed_exts=explode(',', $all_allowed_exts);
            $all_allowed_exts=array_unique($all_allowed_exts);
			
			$file_extension = sp_get_file_extension($_FILES['file']['name']);
            $upload_max_filesize=$upload_setting['upload_max_filesize'][$file_extension];
            $upload_max_filesize=empty($upload_max_filesize)?30485760:$upload_max_filesize;//默认10M
			$savepath='/isbn/'.date('Ymd').'/';
            //上传处理类
            $config=array(
            		'rootPath' => './'.C("UPLOADPATH"),
            		'savePath' => $savepath,
            		'maxSize' => $upload_max_filesize,
            		'saveName'   =>    array('uniqid',''),
            		'exts'       =>    $all_allowed_exts,
            		'autoSub'    =>    false,
            );
			$upload = new \Think\Upload($config);// 
			$info=$upload->upload();
            //开始上传
            if ($info) {
                //上传成功
                $oriName = $_FILES['file']['name'];
                //写入附件数据库信息
                $first = array_shift($info);
				$url = C("TMPL_PARSE_STRING.__UPLOAD__").$savepath.$first['savename'];
				$full_path = SITE_PATH.$url;
				$preview_url = $url;
				
				//执行数据导入
				ini_set('memory_limit', '556M');
				ini_set('max_execution_time', '0');
				vendor('PHPExcel.PHPExcel');
				vendor('PHPExcel.PHPExcel.IOFactory');
				$objReader = \PHPExcel_IOFactory::createReader('Excel5');
				$objPHPExcel = $objReader->load($full_path,$encode='utf-8');
				$data = '';
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow(); // 取得总行数
				$highestColumn = $sheet->getHighestColumn(); // 取得总列数
				for($i=2;$i<=$highestRow;$i++)
				{
					$data[$i]["isbn"] = trim($objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue());
					$data[$i]["bookname"] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
					$data[$i]["price"] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
					$data[$i]["publisher"] = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
					if(empty($data[$i]["isbn"]))continue;
					$where["isbn"] = $data[$i]["isbn"];
					
					$kucun_model = M("kucun");
					$kucun_model->where($where)->save($data[$i]);
					
					$outlist_model = M("kucun_outlist");
					$outlist_model->where($where)->save($data[$i]);
				}
				$total = count($data);
				$this->ajaxReturn(array('code'=>'1','msg'=>"更新成功，共".$total."条！",'status'=>1));
				
            } else {
                $this->ajaxReturn(array('name'=>'','status'=>0,'message'=>$upload->getError()));
            }
		}else{
			$this->error("文件未上传！");
		}
    }
	
	
	//图书快速出库
	public function chuku_one(){
		$this->checkuser();
		$user = session('user');
		$bookid = I('get.bookid','');
		if(!empty($bookid)){
			$where["uid"] = $user['id'];
			$where["id"] = $bookid;
			$bookinfo = M("kucun")->where($where)->find();
			$this->assign('bookinfo',$bookinfo);
		}
		$this->checkuser();
		$user = session('user');
    	$this->display("book:chuku_one");
	}
	
	//单本出库
	public function chuku_one_action(){
		$this->checkuser();
		$user = session('user');
		$isbn = I('post.isbn','');
		$booknum = I('post.booknum','');
		if(empty($isbn)){
			$this->error("ISBN为空，返回请求页面！");
			exit();
		}
		if(empty($booknum)){
			$this->error("出库数量为空！");
			exit();
		}
		
		$where["uid"] = $user['id'];
		$where["isbn"] = $isbn;
		$temp = M("kucun")->where($where)->find();
		
		$data["isbn"] = $temp["isbn"];
		$data["bookname"] =  $temp["bookname"];
		$data["price"] =  $temp["price"];
		$data["booknum"] =  $booknum;
		if(empty($data["isbn"]))continue;
		$data["uid"] = $user['id'];
		$data["outtime"] = date("Y-m-d H:i:s");
		$outlist_model = M("kucun_outlist");
		$outlist_model->add($data);
		
		die("1");
	}
	
	//批量出库_备份
	public function chuku_bak(){
		$this->checkuser();
		$user = session('user');
		//分页
		$page = I('get.page','');
		$starttime = I('get.starttime','');
		$endtime = I('get.endtime','');
		$page = empty($page)?1:$page;
		$pagesize = 30;
		$start = ($page-1)*$pagesize;
		//$limitstr = $start.",".$pagesize;
		
		$outlist_model = M("kucun_outlist");
		if(!empty($starttime)){
			$data['starttime'] = $starttime;
		}else{
			$data['starttime'] = date('Y-m-d 00:00');
		}
		
		if(!empty($endtime)){
			$data['endtime'] = $endtime;
		}else{
			$data['endtime'] = date('Y-m-d 59:59');
		}
		
		$where["uid"] = $user['id'];
		$where["outtime"] = array(array('EGT',$starttime),array('ELT',$endtime),'and'); 
		
		$data['list'] = $outlist_model->where($where)->order(" id desc ")->select();
		
		$data['count'] = $outlist_model->where($where)->count();
		$data['total'] = ceil($data['count']/$pagesize);
		$data['page'] = $page;
		$pageurl = U("index/chuku")."&starttime=".$starttime."&endtime=".$endtime;
		$data['pageurl'] = $pageurl;
		
		$this->assign('data',$data);
    	$this->display("book:chuku");
	}
	
	//单书批量出库
	public function chuku(){
		$this->checkuser();
		$user = session('user');
		
		$isbn = I('get.isbn','');
		$data['isbn'] = $isbn;
		if(empty($isbn)){
			$where["isbn"] = "";
		}
		
		$kucun_model = M("kucun");
		$where["uid"] = $user['id'];
		$where["isbn"] = $isbn;
		
		$data['list'] = $kucun_model->where($where)->limit($limitstr)->order(" booknum desc ")->select();
		
		$data['count'] = $kucun_model->where($where)->count();
		$data['total'] = $kucun_model->where($where)->limit($limitstr)->order(" id desc ")->Sum('booknum');
		$data['total'] = empty($data['total'])?0:$data['total'];
		$data['page'] = $page;
		$pageurl = U("index/chuku")."&starttime=".$starttime."&endtime=".$endtime;
		$data['pageurl'] = $pageurl;
		
		$this->assign('data',$data);
    	$this->display("book:chuku");
	}
	
	//单书批量出库执行
	public function chukuaction(){
		$this->checkuser();
		$user = session('user');
		$idarr = I('post.idarr','');
		$booknumarr = I('post.booknumarr','');
		
		if(empty($idarr)){
			$this->error("ISBN为空，返回请求页面！");
			exit();
		}
		if(empty($booknumarr)){
			$this->error("出库数量为空！");
			exit();
		}
		
		//过滤掉为空的
		foreach( $booknumarr as $key=>$val ){
			if(empty($val)){
				unset($booknumarr[$key]);
				unset($idarr[$key]);
			}
		}
		
		$outlist_model = M("kucun_outlist");
		//插入到出库单中
		foreach( $booknumarr as $key=>$val ){
			$booknum = $booknumarr[$key];//设置的出库本数
			$where["uid"] = $user['id'];
			$where["id"] = $idarr[$key];
			
			$temp = M("kucun")->where($where)->find();
			
			if(empty($temp["isbn"]))continue;
			
			//扣减库存
			if($temp["booknum"]>$booknum){
				M("kucun")->where($where)->setDec("booknum",$booknum);//扣减库存
			}else if($temp["booknum"]==$booknum){
				M("kucun")->where($where)->delete();
			}else{
				$this->error("错误，出库数大于此位置存放！");
				exit();
			}
			
			$data["isbn"] = $temp["isbn"];
			$data["bookname"] =  $temp["bookname"];
			$data["price"] =  $temp["price"];
			$data["location"] =  $temp["location"];
			$data["booknum"] =  $booknum;
			$data["uid"] = $user['id'];
			$data["outtime"] = date("Y-m-d H:i:s");
			$rs = $outlist_model->add($data);
		}
		$this->success("出库完成！",U("index/chuku"));
	}
	
	/*出库数据上传操作*/
	public function chukuup(){
		$this->checkuser();
		$user = session('user');
		
		if ( !empty($_FILES) ) {
			$upload_setting=sp_get_upload_setting();
			$filetypes=array(
				'image'=>array('title'=>'Image files','extensions'=>$upload_setting['image']['extensions']),
				'video'=>array('title'=>'Video files','extensions'=>$upload_setting['video']['extensions']),
				'audio'=>array('title'=>'Audio files','extensions'=>$upload_setting['audio']['extensions']),
				'file'=>array('title'=>'Custom files','extensions'=>$upload_setting['file']['extensions'])
			);
			$all_allowed_exts=array();
            foreach ($filetypes as $mfiletype){
                array_push($all_allowed_exts, $mfiletype['extensions']);
            }
            $all_allowed_exts=implode(',', $all_allowed_exts);
            $all_allowed_exts=explode(',', $all_allowed_exts);
            $all_allowed_exts=array_unique($all_allowed_exts);
			
			$file_extension = sp_get_file_extension($_FILES['file']['name']);
            $upload_max_filesize=$upload_setting['upload_max_filesize'][$file_extension];
            $upload_max_filesize=empty($upload_max_filesize)?30485760:$upload_max_filesize;//默认10M
			$savepath='/ruku/'.date('Ymd').'/';
            //上传处理类
            $config=array(
            		'rootPath' => './'.C("UPLOADPATH"),
            		'savePath' => $savepath,
            		'maxSize' => $upload_max_filesize,
            		'saveName'   =>    array('uniqid',''),
            		'exts'       =>    $all_allowed_exts,
            		'autoSub'    =>    false,
            );
			$upload = new \Think\Upload($config);// 
			$info=$upload->upload();
            //开始上传
            if ($info) {
                //上传成功
                $oriName = $_FILES['file']['name'];
                //写入附件数据库信息
                $first = array_shift($info);
				$url = C("TMPL_PARSE_STRING.__UPLOAD__").$savepath.$first['savename'];
				$full_path = SITE_PATH.$url;
				$preview_url = $url;
				
				//执行数据导入
				ini_set('memory_limit', '556M');
				ini_set('max_execution_time', '0');
				vendor('PHPExcel.PHPExcel');
				vendor('PHPExcel.PHPExcel.IOFactory');
				$objReader = \PHPExcel_IOFactory::createReader('Excel5');
				$objPHPExcel = $objReader->load($full_path,$encode='utf-8');
				$data = '';
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow(); // 取得总行数
				$highestColumn = $sheet->getHighestColumn(); // 取得总列数
				for($i=2;$i<=$highestRow;$i++)
				{
					$data[$i]["isbn"] = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
					$data[$i]["bookname"] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
					$data[$i]["booknum"] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
					if(empty($data[$i]["isbn"]))continue;
					$data[$i]["uid"] = $user['id'];
					$data[$i]["outtime"] = date("Y-m-d H:i:s");
					$outlist_temp_model = M("kucun_outlist_temp");
					$outlist_temp_model->add($data[$i]);
				}
				
				$this->ajaxReturn(array('code'=>'1','msg'=>"导入出库信息成功！",'status'=>1));
				
            } else {
                $this->ajaxReturn(array('name'=>'','status'=>0,'message'=>$upload->getError()));
            }
		}else{
			$this->error("文件未上传！");
		}
    }
	
	//多数批量出库
	public function chuku_pl() {
		$this->checkuser();
		$user = session('user');
		$temp_data_list = '';
		$kucun_model = M("kucun");
		$temp_model = M("kucun_outlist_temp");
		$where['uid'] = $user['id'];
		
		$outlist = $temp_model->field('id,uid,isbn,bookname,price,outtime,sum(booknum) as booknum')->where($where)->group("isbn")->select();
		if(!empty($outlist)){
			//循环出库列表，匹配库存，生成出库方案
			foreach( $outlist as $key=>$val ){
				if( !empty($val['isbn']) ){
					unset($where);unset($data);
					$where["statue"] = 1;
					$where['isbn'] = $val['isbn'];
					$data['uid'] = $user['id'];
					$data['isbn'] = $val['isbn'];
					$data['price'] = $val['price'];
					$data['bookname'] = $val['bookname'];
					$data['booknum'] = $val['booknum'];
					$data['outtime'] = date("Y-m-d H:i:s");
					$count = $val['booknum'];
					
					//判断有无库存
					$outtemp = $kucun_model->where($where)->find();
					if(empty($outtemp)){
						$data['location'] = "缺货";
						$data['booknum'] = $val['booknum'];
						$temp_data_list[] = $data;
						continue;
					}
					
					if($count>1){
						//如果出库本书为多本，优先取多本在一起的
						$where["booknum"] = array("EGT",$count);
						$outtemp = $kucun_model->where($where)->find();
						if(!empty($outtemp)){
							$data['location'] = $outtemp['location'];
							$temp_data_list[] = $data;
						}else{
							//如果没有那么多在一起的书，则优先取多些的，拼凑
							unset($where["booknum"]);
							$outtemp = $kucun_model->where($where)->order("booknum desc")->select();
							foreach( $outtemp as $ckey=>$cval ){
								if($count){
									$count = $count - $cval['booknum'];
									if($count>=0){
										//扣减后如果还需要出库
										$data['booknum'] = $cval['booknum'];
										$data['location'] = $cval['location'];
										$temp_data_list[] = $data;
									}else{
										//扣减后，数量完成，则跳出循环
										$count = $cval['booknum'] + $count;
										$data['booknum'] = $count;
										$data['location'] = $cval['location'];
										$temp_data_list[] = $data;
										break;
									}
								}
							}
						}
					}else{
						$outtemp = $kucun_model->where($where)->find();
						if(!empty($outtemp)){
							$data['location'] = $outtemp['location'];
							$temp_data_list[] = $data;
						}else{
							$data['location'] = "缺货";
							$data['booknum'] = "0";
							$temp_data_list[] = $data;
						}
					}
				}
			}
		}
		$this->assign('data',$temp_data_list);
		$this->display("book:chuku_pl");
	}
	
	//取消批量出库
	public function cancle_chuku_pl(){
		$this->checkuser();
		$user = session('user');
		$temp_model = M("kucun_outlist_temp");
		$where['uid'] = $user['id'];
		$result = $temp_model->where($where)->delete();
		if($result !== false){
			$this->success("取消成功！",U('index/chuku'));
		}else{
			$this->error("取消失败！",U('index/chuku_pl'));
		}
		
	}
	
	//进行批量出库action
	public function chuku_pl_action() {
		$this->checkuser();
		$user = session('user');
		$kucun_model = M("kucun");
		$outlist_model = M("kucun_outlist");
		$temp_model = M("kucun_outlist_temp");
		$where['uid'] = $user['id'];
		
		$outlist = $temp_model->field('id,uid,isbn,bookname,price,outtime,sum(booknum) as booknum')->where($where)->group("isbn")->select();
		if(!empty($outlist)){
			//循环出库列表，匹配库存，生成出库方案
			foreach( $outlist as $key=>$val ){
				if( !empty($val['isbn']) ){
					unset($where);unset($data);
					$where["statue"] = 1;
					$where['isbn'] = $val['isbn'];
					$data['uid'] = $user['id'];
					$data['isbn'] = $val['isbn'];
					$data['price'] = $val['price'];
					$data['bookname'] = $val['bookname'];
					$data['booknum'] = $val['booknum'];
					$data['outtime'] = date("Y-m-d H:i:s");
					$count = $val['booknum'];
					
					//判断有无库存
					$outtemp = $kucun_model->where($where)->find();
					if(empty($outtemp)){
						$data['location'] = "缺货";
						$data['booknum'] = $val['booknum'];
						$temp_data_list[] = $data;
						continue;
					}
					
					if($count>1){
						//如果出库本书为多本，优先取多本在一起的
						$where["booknum"] = array("EGT",$count);
						$outtemp = $kucun_model->where($where)->find();
						if(!empty($outtemp)){
							$data['location'] = $outtemp['location'];
							$outlist_model->add($data);
							
							//扣减库存start
							$cwhere["uid"] = $user['id'];
							$cwhere["id"] = $outtemp['id'];
							if($outtemp["booknum"]>$count){
								M("kucun")->where($cwhere)->setDec("booknum",$count);//扣减库存
							}else if($outtemp["booknum"]==$count){
								M("kucun")->where($cwhere)->delete();
							}else{
								$this->error("错误，出库数大于此位置存放！");
								exit();
							}
							//扣减库存end
							
						}else{
							//如果没有那么多在一起的书，则优先取多些的，拼凑
							unset($where["booknum"]);
							$outtemp = $kucun_model->where($where)->order("booknum desc")->select();
							foreach( $outtemp as $ckey=>$cval ){
								if($count){
									$count = $count - $cval['booknum'];
									if($count>=0){
										//扣减后如果还需要出库
										$data['booknum'] = $cval['booknum'];
										$data['location'] = $cval['location'];
										$outlist_model->add($data);
										
										//扣减库存start
										$cwhere["uid"] = $user['id'];
										$cwhere["id"] = $cval['id'];
										M("kucun")->where($cwhere)->delete();
										//扣减库存end
										
									}else{
										//扣减后，数量完成，则跳出循环
										$count = $cval['booknum'] + $count;
										$data['booknum'] = $count;
										$data['location'] = $cval['location'];
										$outlist_model->add($data);
										
										$cwhere["uid"] = $user['id'];
										$cwhere["id"] = $outtemp['id'];
										M("kucun")->where($cwhere)->setDec("booknum",$count);//扣减库存
										
										break;
									}
								}
							}
						}
					}else{
						$outtemp = $kucun_model->where($where)->find();
						if(!empty($outtemp)){
							$data['location'] = $outtemp['location'];
							$outlist_model->add($data);
						}else{
							$data['location'] = "缺货";
							$data['booknum'] = "0";
						}
					}
				}
			}
		}
		
		unset($where);
		$where['uid'] = $user['id'];
		$result = M("kucun_outlist_temp")->where($where)->delete();
		if($result !== false){
			$this->success("批量出库成功，跳转至出库打印页面！",U('index/printlist'));
		}else{
			$this->error("取消失败！",U('index/chuku_pl'));
		}
		
	}
	
	//图书信息维护列表页面
	public function list_book(){
		$this->checkuser();
		$user = session('user');
		//分页
		$isbn = I('get.isbn','');
		$bookname = I('get.bookname','');
		$page = I('get.page','');
		$page = empty($page)?1:$page;
		$pagesize = 20;
		$start = ($page-1)*$pagesize;
		$limitstr = $start.",".$pagesize;
		
		$kucun_model = M("kucun");
		$where["statue"] = 1;
		$where["uid"] = $user['id'];
		if(!empty($isbn)){
			$data["searchisbn"] = $isbn;
			$data["searchinfo"] = "&isbn=".$isbn;
			$where["isbn"] = $isbn;
		}
		if(!empty($bookname)){
			$data["searchbookname"] = $bookname;
			$data["searchinfo"] = "&bookname=".$bookname;
			$where["bookname"] = array('like','%'.$bookname.'%');
		}
		$data['list'] = $kucun_model->where($where)->order("id desc ")->limit($limitstr)->select();
		$data['count'] = $kucun_model->where($where)->count();
		$data['total'] = ceil($data['count']/$pagesize);
		$data['page'] = $page;
		$pageurl = U("index/list_book").$data['searchinfo'];
		$data['pageurl'] = $pageurl;
		
		$this->assign('data',$data);
    	$this->display("book:list_book");
	}
	
	//图书库位管理
	public function list_kuwei(){
		$this->checkuser();
		$user = session('user');
		
		
		//分页
		$location = I('get.location','');
		$page = I('get.page','');
		$page = empty($page)?1:$page;
		$pagesize = 20;
		$start = ($page-1)*$pagesize;
		$limitstr = $start.",".$pagesize;
		
		$kucun_model = M("kucun");
		$where["statue"] = 1;
		$where["uid"] = $user['id'];
		
		
		if(!empty($location)){
			$data["searchlocation"] = $location;
			$where["location"] = $location;
		}
		
		$data['list'] = $kucun_model->where($where)->group("location")->limit($limitstr)->select();
		foreach( $data['list'] as $key=>$val ){
			$where["location"] = $val["location"];
			$data['list'][$key]['count'] = $kucun_model->where($where)->count();
		}
		$data['count'] = $kucun_model->where($where)->group("location")->count();
		$data['total'] = ceil($data['count']/$pagesize);
		$data['page'] = $page;
		$pageurl = U("index/list_kuwei").$data['searchinfo'];
		$data['pageurl'] = $pageurl;
		
		$this->assign('data',$data);
    	$this->display("book:list_kuwei");
	}
	
	//删除库位下书籍
	public function delkuwei(){
		$this->checkuser();
		$user = session('user');
		$kucun_model = M("kucun");
		$location = I('get.location','');
		if(empty($location)){
			$this->error("库位错误！");
			exit();
		}
		$where["location"] = $location;
		$where["uid"] = $user['id'];
		$rs = $kucun_model->where($where)->delete();
		$this->success("库位删除成功！",U('index/list_kuwei'));
	}
	
	//图书库存信息导出
	public function list_book_output(){
		set_time_limit(0);
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', '0');
		$this->checkuser();
		$user = session('user');
		$kucun_model = M("kucun");
		$where["statue"] = 1;
		$where["uid"] = $user['id'];
		$data['list'] = $kucun_model->where($where)->order("id desc ")->field("isbn,location,SUM(booknum) AS booknum,bookname,price")->group("isbn")->select();
		
		/*
		foreach( $data['list'] as $key=>$val ){
			$data['list'][$key]["isbn"] = " ".$data['list'][$key]["isbn"];
		}*/
		$temp[0]["isbn"] = "ISBN";
		$temp[0]["location"] = "位置";
		$temp[0]["booknum"] = "数量";
		$temp[0]["bookname"] = "书名";
		$temp[0]["price"] = "价格";
		array_splice($data['list'],0,0,$temp);
		
		//执行数据导出
		Vendor('PHPExcel.PHPExcel');
		$filename = '库存数据_'.date('Y-m-d').'.xls';
		$phpexcel = new \PHPExcel();
		$phpexcel->getProperties()
		->setCreator("eatpeach")
		->setLastModifiedBy("eatpeach")
		->setTitle("Office 2007 XLSX Test Document")
		->setSubject("Office 2007 XLSX Test Document")
		->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
		->setKeywords("office 2007 openxml php")
		->setCategory("Test result file");
		
		$phpexcel->getActiveSheet()->fromArray($data['list']);
		$phpexcel->getActiveSheet()->getStyle('A')->getNumberFormat()->setFormatCode('@');
		$phpexcel->getActiveSheet()->setTitle('Sheet1');
		$phpexcel->setActiveSheetIndex(0);
		
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=$filename");
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1');
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		vendor('PHPExcel.PHPExcel.IOFactory');
		$objwriter = \PHPExcel_IOFactory::createWriter($phpexcel,'Excel2007');
		$objwriter->save('php://output');
		exit;
		
	}
	
	//图书信息编辑页面
	public function edite_book(){
		$this->checkuser();
		$user = session('user');
		//分页
		$bookid = I('get.bookid','');
		if(empty($bookid)){
			$this->error("图书ID没有传递，返回请求页面！");
			exit();
		}
		$kucun_model = M("kucun");
		$where["uid"] = $user['id'];
		$where["id"] = $bookid;
		$check = $kucun_model->where($where)->count();
		if(empty($check)){
			$this->error("图书ID不存在或者该书不属于您！");
			exit();
		}
		$data['bookinfo'] = $kucun_model->where($where)->find();
		$this->assign('data',$data);
    	$this->display("book:edite_book");
	}
	
	//图书信息编辑操作
	public function editeaction_book(){
		$this->checkuser();
		$user = session('user');
		//分页
		$bookid = I('post.bookid','');
		$data['bookname'] = I('post.bookname','');
		$data['booknum'] = I('post.booknum','');
		$data['location'] = I('post.location','');
		$data['addtime'] = I('post.addtime','');
		$data['publisher'] = I('post.publisher','');
		$data['price'] = I('post.price','');
		if(empty($bookid)){
			$this->error("图书ID没有传递，返回请求页面！");
			exit();
		}
		$kucun_model = M("kucun");
		$where["uid"] = $user['id'];
		$where["id"] = $bookid;
		$check = $kucun_model->where($where)->count();
		if(empty($check)){
			$this->error("图书ID不存在或者该书不属于您！");
			exit();
		}
		$rs = $kucun_model->where($where)->save($data);
		
		/*同书号信息更新*/
		$info = $kucun_model->where($where)->field('isbn')->find();
		unset($where["id"]);
		unset($data['booknum']);
		unset($data['location']);
		unset($data['addtime']);
		$where["isbn"] = $info["isbn"];
		$kucun_model->where($where)->save($data);
		/*出库表中信息更新*/
		$outlist_model = M("kucun_outlist");
		$outlist_model->where($where)->save($data);
		
		if($rs){
			$this->success("更新成功！",U('index/list_book'));
		}else{
			$this->error("更新失败！");
		}
	}
	
	
	//删除某条出库信息
	public function delchuku(){
		$this->checkuser();
		$user = session('user');
		$chukuid = I('get.chukuid','');
		if(empty($chukuid)){
			$this->error("库存ID没有传递，返回请求页面！");
			exit();
		}
		$outlist = M("kucun_outlist");
		$where["uid"] = $user['id'];
		$where["id"] = $chukuid;
		$check = $outlist->where($where)->count();
		if(empty($check)){
			$this->error("库存ID不存在或者该书不属于您！");
			exit();
		}
		
		$outlist->where($where)->delete();
		//删除该条出库信息后，还需要将出库方案临时表清空掉，出库信息锁定的需要恢复正常
		$temp_model = M("kucun_outlist_temp");
		$temp_model->where("uid=".$user['id'])->delete();
		$data['isprint'] = array('exp','null');
		$outlist->where("isprint=2")->save($data);
		
		$this->success("删除成功！");
	}
	
	
	//合并系统中的同ISBN同位置的数据
	public function cleandata(){
		set_time_limit(0);
		//分页
		$page = I('get.page','');
		$maxid = I('get.maxid','');
		$page = empty($page)?1:$page;
		if($page==1){
			$starttime = strtotime("now");
		}else{
			$starttime = I('get.starttime','');
		}
		$pagesize = 1000;
		$start = ($page-1)*$pagesize;
		$limitstr = "0,".$pagesize;
		
		
		if( !empty($maxid) ){
			$maxstr = " AND id<= ".$maxid;
		}
		
		$this->checkuser();
		$user = session('user');
		//group by isbn
		$kucun_model = M("kucun");
		
		
		$datalist = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' ".$maxstr."  ")->group('isbn')->limit($limitstr)->order(" id DESC ")->select();
		$maxarr = end($datalist);
		
		$maxid = $maxarr['id'];
		if( empty($maxid) ){
			$this->error("错误，请重新发起请求！");
			exit();
		}
		$minid = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' ")->min("id");
		if( $maxid<=$minid ){
			$usetime = strtotime("now")-$starttime;
			$this->success("处理完成(耗时：".$usetime."秒)！","",999999999);
			die();
		}
		
		if(empty($datalist)){
			$usetime = strtotime("now")-$starttime;
			$this->success("处理完成(耗时：".$usetime."秒)！","",999999999);
			die();
		}
		
		foreach( $datalist as $key=>$val ){
			$one = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' AND isbn = '".$val['isbn']."' ")->group('location')->select();
			foreach( $one as $okey=>$oval ){
				$count = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' AND isbn = '".$val['isbn']."' AND location = '".$oval['location']."' ")->count();
				if($count>1){
					$data = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' AND isbn = '".$val['isbn']."' AND location = '".$oval['location']."' ")->find();
					$total = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' AND isbn = '".$val['isbn']."' AND location = '".$oval['location']."' ")->sum("booknum");
					$data['booknum'] = $total;
					$data['id'] = null;
					if($total>1){
						//清掉库存
						$rs = $kucun_model->where(" statue=1 AND uid ='".$user['id']."' AND isbn = '".$val['isbn']."' AND location = '".$oval['location']."' ")->delete();
						//插入合并后库存
						$kucun_model->add($data);
					}
				}
			}
		}
		$nextpage = $page + 1;
		$usetime = strtotime("now")-$starttime;
		$this->success("处理完成，跳转到第".$nextpage."页进行处理(已耗时：".$usetime."秒)！",U('index/cleandata')."&page=".$nextpage."&maxid=".$maxid."&starttime=".$starttime);
	}
	
	//修改密码
	public function modifypwd(){
		$this->checkuser();
		$user = session('user');
		//更新session
		$where['id'] = $user['id'];
		$user = M("users")->where($where)->find();
		$this->assign('user',$user);
    	$this->display("book:edite_pwd");
	}
	
	//修改密码操作
	public function modifypwdaction(){
		$this->checkuser();
		$user = session('user');
		$where['id'] = $user['id'];
		$data["user_login"] = I('post.user_login','');
		$data["mobile"] = I('post.mobile','');
		$data["user_nicename"] = I('post.user_nicename','');
		if(empty($data["user_login"])){
			$this->error("账号不能为空！");
			exit();
		}
		
		$pwd = I('post.user_pass','');
		$repwd = I('post.reuser_pass','');
		$reset = 0;
		if(!empty($pwd)){
			$data["user_pass"] = sp_password($pwd);
			if(empty($pwd)){
				$this->error("密码不能为空！");
				exit();
			}
			if($pwd!=$repwd){
				$this->error("两次密码输入不一致！");
				exit();
			}
			$reset = 1;
		}
		$rs =  M("users")->where($where)->save($data);
		if($rs){
			if($reset){
				$this->success("修改成功，请在推出后重新登录！",U('index/logout'));
				exit();
			}
			$this->success("更新成功！");
		}else{
			$this->error("更新失败！");
		}
		
	}
	
	//系统登录页面
	public function login(){
		$verrifycode = $this->randomcode();
		session('verrifycode',$verrifycode);
		$redirect = $_SERVER['HTTP_REFERER'];
	    session('login_http_referer',$redirect);
	    if(sp_is_user_login()){ //已经登录时直接跳到首页
	        redirect(U('index/index'));
			exit();
	    }else{
			$this->assign("verrifycode",$verrifycode);
			$this->display("book:login");
		}
	}
	
	//随机验证字符串
	private function randomcode(){
		$chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$randomcode = ""; 
		for ($i = 0;$i<5; $i++ )
		{ 
			$randomcode .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
		} 
		return $randomcode; 
	}
	
	//系统登录操作
	public function dologin(){
		session("user",null);
		//验证码
		$verrify = strtolower(I("post.verify"));
		$ss = strtolower(session('verrifycode'));
    	if($ss!=$verrify){
    		$this->error("验证码输入错误！");
    	}else{
			$users_model = M('Users');
			$where['user_login'] = I('post.user_login');
			$password = I('post.password');
			$result = $users_model->where($where)->find();
			
			if(!empty($result)){
				if(sp_compare_password($password, $result['user_pass'])){
					session('user',$result);
					//写入此次登录信息
					$data = array(
						'last_login_time' => date("Y-m-d H:i:s"),
						'last_login_ip' => get_client_ip(0,true),
					);
					$users_model->where(array('id'=>$result["id"]))->save($data);
					$session_login_http_referer = session('login_http_referer');
					$redirect=empty($session_login_http_referer)?__ROOT__."/":$session_login_http_referer;
					//$this->success("登录成功！",U('index/index'));
					redirect(U('index/index'));
				}else{
					$this->error("密码错误！");
				}
			}else{
				$this->error("账户不存在！");
			}
		}
    }
	
	//退出登录
    public function logout(){
    	$login_success=false;
    	session("user",null);//只有前台用户退出
    	$logouturl = __ROOT__;
		$this->success("退出成功！", $logouturl);
    }
	
	//检查是否有权限进入程序
	private function checkuser(){
		$user = session('user');
		if(empty($user)){
			redirect(U('index/login'));
			exit();
		}
		
		/*检测下session中的用户statue*/
		$user_model = M("Users");
		$cc = $user_model->where("id=".$user['id'])->find();
		if($cc['user_status']!="1"){
			$this->error("您的账户被锁定，即将退回上一步！");
			exit();
		}
		
		if($user['user_type']!="1"){
			$this->error("您不是管理员账户，即将返回首页！");
			exit();
		}else{
			return $user;
		}
	}
	
	/*获取豆瓣接口*/
	private function GetDouBanAPI($url) {
		$refer = "https://www.douban.com/";
		$agent = "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1";
		$ip = $this->GetIP();
		/*
		if($ip=="127.0.0.1"){
			$ip = "202.106.0.21";//百度的IP
		}
		*/
		$iparr = array('61.136.195.209','61.136.195.210','61.136.195.241','61.136.195.246','61.136.195.249','61.136.195.250','61.136.195.251','61.136.195.252','61.136.196.9','61.136.196.11','61.136.196.101','61.136.196.102','61.136.196.121','61.136.196.122','61.136.196.131','61.136.196.132','61.136.196.137','61.136.196.138','61.136.196.161','61.136.196.162','61.136.196.193','61.136.196.194','61.136.196.196','61.136.196.197','61.136.196.213','61.136.196.214','61.136.196.217','61.136.196.218','61.136.196.229','61.136.196.230','61.136.196.237','61.136.196.238','61.136.196.249','61.136.196.250','61.136.197.1','61.136.197.2','61.136.197.3','61.136.197.4','61.136.197.5','61.136.197.6','61.136.197.7','61.136.197.8','61.136.197.9','61.136.197.10','61.136.197.11','61.136.197.12','61.136.197.13','61.136.197.14','61.136.197.15','61.136.197.16','61.136.197.17','61.136.197.18','61.136.197.19','61.136.197.20','61.136.197.21','61.136.197.22','61.136.197.23','61.136.197.24','61.136.197.25','61.136.197.26','61.136.197.27','61.136.197.29','61.136.197.30','61.136.197.31','61.136.197.32','61.136.197.33','61.136.197.34','61.136.197.35','61.136.197.36','61.136.197.37','61.136.197.40','61.136.197.41','61.136.197.43','61.136.197.44','61.136.197.45','61.136.197.46','61.136.197.47','61.136.197.48','61.136.197.49','61.136.197.50','61.136.197.52','61.136.197.53','61.136.197.54','61.136.197.55','61.136.197.56','61.136.197.57','61.136.197.72','61.136.197.73','61.136.197.219','61.136.197.220','61.136.197.255','61.136.198.12','61.136.198.13','61.136.198.21','61.136.198.22','61.136.198.27','61.136.198.28','61.136.198.29','61.136.198.30','61.136.198.37','61.136.198.38','61.136.198.45','61.136.198.46','61.136.198.57','61.136.198.58','61.136.198.61','61.136.198.62','61.136.198.115','61.136.198.116','61.136.198.117','61.136.198.118','61.136.198.119','61.136.198.127','61.136.198.255','61.136.199.65','61.136.199.66','61.136.199.130','61.136.199.131','61.136.199.136','61.136.199.137','61.136.199.145','61.136.199.146','61.136.199.152','61.136.199.153','61.136.199.154','61.136.199.155','61.136.199.158','61.136.199.159','61.136.199.160','61.136.199.161','61.136.199.162','61.136.199.163','61.136.199.166','61.136.199.167','61.136.199.168','61.136.199.169','61.136.199.170','61.136.199.171','61.136.199.172','61.136.199.177','61.136.199.178','61.136.199.179','61.136.199.180','61.136.199.183','61.136.199.184','61.136.199.185','61.136.199.189','61.136.199.190','61.136.199.191','61.136.199.192','61.136.199.193','61.136.199.195','61.136.199.196','61.136.199.199','61.136.199.200','61.136.199.201','61.136.199.213','61.136.199.214','61.136.199.219','61.136.199.220','61.136.199.223','61.136.199.224','61.136.199.229','61.136.199.230','61.136.199.232','61.136.199.233','61.136.199.243','61.136.199.244','61.136.201.255','61.136.202.255','61.136.203.4','61.136.203.5','61.136.203.29','61.136.203.30','61.136.203.37','61.136.203.38','61.136.203.65','61.136.203.66','61.136.203.98','61.136.203.99','61.136.203.137','61.136.203.138','61.136.204.184','61.136.204.189','61.136.204.190','61.136.204.217','61.136.204.218','61.136.204.234','61.136.204.235','61.136.204.250','61.136.204.251','61.136.205.127','61.136.205.131','61.136.205.132','61.136.206.69','61.136.206.70','61.136.207.137','61.136.207.138','61.136.207.139','61.136.207.141','61.136.207.255','61.136.208.127','61.136.210.84','61.136.210.85','61.136.210.86','61.136.210.87','61.136.210.89','61.136.210.90','61.136.210.91','61.136.210.113','61.136.210.114','61.136.210.255','61.136.212.67','61.136.212.68','61.136.212.89','61.136.212.90','61.136.212.107','61.136.212.108','61.136.212.109','61.136.212.110','61.136.212.111','61.136.212.112','61.136.212.255','61.136.213.127','61.136.215.255','61.136.216.24','61.136.216.25','61.136.217.118','61.136.217.119','61.136.217.122','61.136.217.123','61.136.221.34','61.136.221.35','61.136.221.37','61.136.221.38','61.136.221.39','61.136.221.40','61.136.221.41','61.136.221.42','61.136.221.43','61.136.221.44','61.136.221.45','61.136.221.97','61.136.221.98','61.136.221.99','61.136.221.100','61.136.221.101','61.136.221.102','61.136.221.121','61.136.221.122','61.136.221.123','61.136.221.124','61.136.221.125','61.136.221.126','61.136.221.132','61.136.221.133','61.136.221.134','61.136.221.135','61.136.221.137','61.136.221.138','61.136.221.139','61.136.221.140','61.136.221.141','61.136.221.170','61.136.221.171','61.136.221.193','61.136.221.194','61.136.221.195','61.136.221.196','61.136.221.197','61.136.221.198','61.136.221.201','61.136.221.202','61.136.221.203','61.136.221.204','61.136.221.205','61.136.221.206','61.136.221.225','61.136.221.226','61.136.221.227','61.136.221.228','61.136.221.229','61.136.221.233','61.136.221.234','61.136.221.235','61.136.221.255','61.136.222.234','61.136.222.235','61.136.223.1','61.136.223.2','61.136.223.3','61.136.223.4','61.136.223.5','61.136.223.10','61.136.223.13','61.136.223.65','61.136.223.66','61.136.223.67','61.136.223.68','61.136.223.69','61.136.223.70','61.136.223.71','61.136.223.72','61.136.223.73','61.136.223.74','61.136.223.75','61.136.223.77','61.136.223.78','61.136.223.79','61.136.223.80','61.136.223.81','61.136.223.82','61.136.223.83','61.136.223.84','61.136.223.85','61.136.223.91','61.136.223.92','61.136.223.129','61.136.223.130','61.136.223.136','61.136.223.137','61.136.223.138','61.136.223.139','61.136.223.141','61.136.223.142','61.136.223.143','61.136.223.144','61.136.223.146','61.136.223.147','61.136.223.151','61.136.223.152','61.136.223.163','61.136.223.164','61.136.223.165','61.136.223.166','61.136.223.167','61.136.223.168','61.136.223.169','61.136.223.178','61.136.223.179','61.136.223.182','61.136.223.183','61.136.223.209','61.136.223.210','61.136.223.217','61.136.223.219','61.136.224.255','61.136.225.255','61.136.226.122','61.136.226.123','61.136.226.192','61.136.226.233','61.136.226.234','61.136.226.255','61.136.227.96','61.136.227.97','61.136.229.96','61.136.229.97','61.136.229.134','61.136.229.135','61.136.229.255','61.136.231.255','61.136.232.255','61.136.233.255','61.136.234.1','61.136.234.2','61.136.234.4','61.136.234.5','61.136.234.18','61.136.234.19','61.136.234.20','61.136.236.145','61.136.236.146','61.136.236.255','61.136.238.255','61.136.241.0','61.136.241.1','61.136.241.2','61.136.241.3','61.136.241.4','61.136.241.5','61.136.241.7','61.136.241.8','61.136.241.9','61.136.241.11','61.136.241.20','61.136.241.65','61.136.241.66','61.136.241.67','61.136.241.68','61.136.241.69','61.136.241.70','61.136.241.71','61.136.241.72','61.136.241.73','61.136.241.74','61.136.241.75','61.136.241.76','61.136.241.77','61.136.241.78','61.136.241.79','61.136.241.80','61.136.241.81','61.136.241.82','61.136.241.83','61.136.241.84','61.136.241.85','61.136.241.86','61.136.241.87','61.136.241.88','61.136.241.89','61.136.241.90','61.136.241.91','61.136.241.92','61.136.241.93','61.136.241.94','61.136.241.95','61.136.241.96','61.136.241.97','61.136.241.98','61.136.241.99','61.136.241.101','61.136.241.102','61.136.241.103','61.136.241.104','61.136.241.105','61.136.241.106','61.136.241.108','61.136.241.109','61.136.241.110','61.136.241.111','61.136.241.112','61.136.241.113','61.136.241.114','61.136.241.115','61.136.241.116','61.136.241.117','61.136.241.118','61.136.241.119','61.136.241.120');
		$index = array_rand($iparr,1);
		$ip = $iparr[$index];
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_REFERER, $refer);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.$ip, 'CLIENT-IP:'.$ip));
		curl_setopt($curl, CURLOPT_USERAGENT,$agent);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
	}
	
	//httpget
	private function httpGet($url) {
		$refer = "https://www.baidu.com/";
		$agent = "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1";
		$ip = $this->GetIP();
		if($ip=="127.0.0.1"){
			$ip = "202.106.0.20";//百度的IP
		}
		
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_REFERER, $refer);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.$ip, 'CLIENT-IP:'.$ip));
		curl_setopt($curl, CURLOPT_USERAGENT,$agent);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
	}
	
	/*获取真实IP*/
	private function GetIP(){
		$proxy="";
		$IP = "";
		if (isSet($_SERVER)){
				if (isSet($_SERVER["HTTP_X_FORWARDED_FOR"])) 
				{
						$IP = $_SERVER["HTTP_X_FORWARDED_FOR"];
						$proxy  = $_SERVER["REMOTE_ADDR"];
				} 
				elseif (isSet($_SERVER["HTTP_CLIENT_IP"])) 
				{
						$IP = $_SERVER["HTTP_CLIENT_IP"];
				} 
				else
				{
						$IP = $_SERVER["REMOTE_ADDR"];
				}
		} 
		else 
		{
				if ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) 
				{
						$IP = getenv( 'HTTP_X_FORWARDED_FOR' );
						$proxy = getenv( 'REMOTE_ADDR' );
				} 
				elseif ( getenv( 'HTTP_CLIENT_IP' ) ) 
				{
						$IP = getenv( 'HTTP_CLIENT_IP' );
				} 
				else 
				{
						$IP = getenv( 'REMOTE_ADDR' );
				}
		}
		if (strstr($IP, ',')) 
		{
		   $ips = explode(',', $IP);
		   $IP = $ips[0];
		}
		return $IP;
	}
}


